<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--订单数据-->
      <el-col :span="24" :xs="24">

        <!-- 搜索 -->
        <template>
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="订单编号" prop="orderNo">
              <el-input
                v-model="queryParams.orderNo"
                placeholder="请输入订单编号"
                clearable
                style="width: 240px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="打赏方式" prop="rewardType">
              <el-select
                v-model="queryParams.rewardType"
                placeholder="打赏方式"
                clearable
                style="width: 240px"
              >
                <el-option
                  v-for="dict in dict.type.app_reward_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="交易状态" prop="payStatus">
              <el-select
                v-model="queryParams.payStatus"
                placeholder="交易状态"
                clearable
                style="width: 240px"
              >
                <el-option
                  v-for="dict in dict.type.app_pay_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="是否分销" prop="isDistribution">
              <el-select
                v-model="queryParams.isDistribution"
                placeholder="是否分销"
                clearable
                style="width: 240px"
              >
                <el-option
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="店铺ID" prop="shopId" v-if="$store.getters && $store.getters.admin">
              <el-input
                v-model="queryParams.shopId"
                placeholder="请输入店铺ID"
                clearable
                style="width: 240px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="创建时间">
              <el-date-picker
                v-model="dateRange"
                style="width: 240px"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </template>

        <!-- 按钮操作栏 -->
        <template>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
                v-hasPermi="['order:goods:add']"
              >新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                plain
                icon="el-icon-delete"
                size="mini"
                :disabled="multiple"
                @click="handleDelete"
                v-hasPermi="['order:goods:remove']"
              >删除</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="warning"
                plain
                icon="el-icon-download"
                size="mini"
                @click="handleExport"
                v-hasPermi="['order:goods:export']"
              >导出</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
          </el-row>
        </template>

        <!-- 表格 -->
        <template>
          <el-table v-loading="loading" :data="orderGoodsList" @selection-change="handleSelectionChange" @sort-change="handleSortChange">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="订单编号" align="center" key="orderNo" prop="orderNo" width="230" />
            <el-table-column label="店员" align="center" key="employeeUserId" prop="employeeUserId" :show-overflow-tooltip="true" min-width="180" >
              <template slot-scope="scope">
                <div class="flex-align-center" v-if="scope.row.employeeUser">
                  <el-avatar shape="circle" size="medium" :src="scope.row.employeeUser.avatar" alt="404"></el-avatar>
                  <div class="mgl5 font-14">{{scope.row.employeeUser.nickName}}</div>
                </div>
                <div v-else>-</div>
              </template>
            </el-table-column>
            <el-table-column label="客户" align="left" key="orderUserId" prop="orderUserId" :show-overflow-tooltip="true" width="120" >
              <template slot-scope="scope">
                <div class="flex-align-center" v-if="scope.row.customerUser">
                  <el-avatar shape="circle" size="medium" :src="scope.row.customerUser.avatar" alt="404"></el-avatar>
                  <div class="mgl5 font-14">{{scope.row.customerUser.nickName}}</div>
                </div>
                <div v-else>-</div>
              </template>
            </el-table-column>
            <el-table-column label="礼物" align="center" key="giftId" prop="giftId" :show-overflow-tooltip="true" width="120" >
              <template slot-scope="scope">
                <div class="flex-align-center" v-if="scope.row.giftId">
                <!-- <div class="flex-align-center"> -->
                  <el-image shape="square" size="medium" style="width: 40px; height: 40px" :src="getGiftInfo(scope.row.giftId).handbook.staticImage" alt="404"></el-image>
                  <div class="mgl5 font-14">{{getGiftInfo(scope.row.giftId).handbook.handbookTitle}}</div>
                </div>
                <div v-else>-</div>
              </template>
            </el-table-column>
            <el-table-column label="打赏数量" align="center" key="giftNum" prop="giftNum" :show-overflow-tooltip="true"/>
            <el-table-column label="支付金额" align="center" key="actualAmount" prop="actualAmount" sortable="custom" :sort-orders="['descending', 'ascending']" width="120"/>
            <el-table-column label="打赏方式" align="center" key="rewardType">
              <template slot-scope="scope">
                <dict-tag :noType="true" :options="dict.type.app_reward_type" :value="scope.row.rewardType"/>
              </template>
            </el-table-column>
            <el-table-column label="支付方式" align="center" key="payType" width="120">
              <template slot-scope="scope">
                <dict-tag :noType="true" :options="dict.type.app_pay_type" :value="scope.row.payType"/>
              </template>
            </el-table-column>
            <el-table-column label="交易状态" align="center" key="payStatus" prop="payStatus" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.app_pay_status" :value="scope.row.payStatus"/>
              </template>
            </el-table-column>
            <!-- <el-table-column label="是否分销" align="center" key="isDistribution">
              <template slot-scope="scope">
                <dict-tag :noType="true" :options="dict.type.sys_yes_no" :value="scope.row.isDistribution"/>
              </template>
            </el-table-column> -->
            <el-table-column label="联系方式" align="center" key="wxId" prop="wxId" :show-overflow-tooltip="true"/>
            <el-table-column label="店铺名称" prop="shopInfo.shopName" min-width="120" v-if="$store.getters && $store.getters.admin" />
            <el-table-column label="创建时间" align="center" prop="createTime" sortable="custom" :sort-orders="['descending', 'ascending']" width="160">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              align="center"
              fixed="right"
              width="160"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <!-- <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['order:gift:edit']"
                >修改</el-button> -->
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-view"
                  @click="handleView(scope.row,scope.index)"
                  v-hasPermi="['order:gift:list']"
                >详细</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['order:gift:remove']"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </template>

      </el-col>
    </el-row>

    <!-- 订单详细 -->
    <el-dialog title="订单详细" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" label-width="100px" size="mini">
        <el-row>
          <el-col :span="8">
            <el-form-item label="是否匿名">
              <div v-if="form.isAnonymous === 'Y'">是</div>
              <div v-else-if="form.isAnonymous === 'N'">否</div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="留言">{{ form.remark }}</el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="open = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOrderGift, getOrderGift, delOrderGift, addOrderGift, updateOrderGift } from "@/api/order/gift";
import { listGift } from "@/api/market/gift";
import { getToken } from "@/utils/auth";

export default {
  name: "OrderGift",
  dicts: ['app_pay_type', 'app_reward_type', 'sys_yes_no', 'app_pay_status'],
  components: { },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单表格数据
      orderGoodsList: null,
      // 礼物列表
      giftList: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 订单导入参数
      upload: {
        // 是否显示弹出层（订单导入）
        open: false,
        // 弹出层标题（订单导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的订单数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/orderGoods/orderGoods/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNo: undefined,
        status: undefined,
        payStatus: undefined,
        isRate: undefined,
        isAccept: undefined,
        isDistribution: undefined,
        acceptType: undefined,
        ordergoodsLevelId: undefined,
        goodsUnitId: undefined,
        goodsProjectId: undefined,
        shopId: undefined,
        orderByColumn: 'createTime',
        isAsc: 'descending',
      },
      // 表单校验
      rules: {
      }
    };
  },
  watch: {
  },
  created() {
    Promise.all([this.getGiftList()]).then((values) => {
        this.getList();
      });
  },
  methods: {
    /** 查询订单列表 */
    getList() {
      this.loading = true;
      listOrderGift(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.orderGoodsList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    /** 查询礼物列表 */
    getGiftList() {
      let that = this;
      return new Promise((resolve, reject)=>{
        listGift(this.addDateRange({ pageNum: 1, pageSize: 10000}, null)).then(response => {
          that.giftList = response.rows;
          resolve(that.giftList)
        });
      })
    },
    getGiftInfo(giftId){
      let info = {}
      this.giftList.forEach(v=>{
        if(v.giftId === giftId){
          info = v
        }
      })
      return info
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        orderNo: undefined,
        orderGoodsPrice: undefined,
        orderGoodsPriceNight: undefined,
        goodsTitle: undefined,
        ordergoodsLevelId: undefined,
        goodsUnitId: undefined,
        goodsProjectId: undefined,
        status: "0",
        remark: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderNo);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      getOrderGift().then(response => {
        this.open = true;
        this.title = "添加订单";
        this.form.password = this.initPassword;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const orderNo = row.orderNo || this.ids;
      getOrderGift(orderNo).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改订单";
      });
    },
    /** 排序触发事件 */
    handleSortChange(column, prop, order) {
      this.queryParams.orderByColumn = column.prop;
      this.queryParams.isAsc = column.order;
      this.getList();
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let params = JSON.parse(JSON.stringify(this.form))
          if (this.form.orderNo != undefined) {
            updateOrderGift(params).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrderGift(params).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const orderNos = row.orderNo || this.ids;
      this.$modal.confirm('是否确认删除订单编号为"' + orderNos + '"的数据项？').then(function() {
        return delOrderGift(orderNos);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('orderGoods/orderGoods/export', {
        ...this.queryParams
      }, `orderGoods_${new Date().getTime()}.xlsx`)
    },
    /** 详细按钮操作 */
    handleView(row) {
      this.open = true;
      this.form = row;
    },
  }
};
</script>
